package com.ybg.share.framework;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.ybg.framework.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler implements InitializingBean {
    @Autowired
    private HttpServletRequest request;
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<?> handleException(Exception exception) {
        logger.error("{}", exception);
        if (exception instanceof MybatisPlusException) {
            return new R(R.FAIL, "mybatis error");
        }

        if (exception.getClass().getName().contains("MybatisPlusException")) {
            return new R(R.FAIL, "mybatis error");
        }
        return R.fail("发生错误",exception);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
